package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.core.service.*;
import com.wondertek.poms.dao.bo.ContentMinBo;
import com.wondertek.poms.dao.po.*;
import com.wondertek.poms.dao.pojo.ContentPojo;
import com.wondertek.poms.dao.repo.IContentDao;
import com.wondertek.poms.dao.repo.IPrdContDao;
import com.wondertek.poms.dao.vo.ContentBcVo;
import com.wondertek.poms.dao.vo.ImageVo;
import com.wondertek.poms.dao.vo.PrdContDetailVo;
import com.wondertek.poms.dao.vo.PrdContMinVo;
import com.wondertek.poms.transform.xmlvo.DisplayFileFromXml;
import com.wondertek.poms.transform.xmlvo.MediaFileFromXml;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p><b>contentServiceImpl Description:</b> service层实现 </p>
 *
 * @author 窦再兴
 * <p><b>DATE</b> 2020-10-21 17:28:27</p>
 */
@Service
@Scope("prototype")
public class ContentServiceImpl extends ServiceImpl<Content, Long> implements IContentService {
	@Autowired
	private IContentDao contentDao;
	@Autowired
	private IPrdContDao prdContDao;
	@Autowired
	private IMediaFileService mediaFileService;
	@Autowired
	private IImageService imageService;
	@Autowired
	private IDisplayFileService displayFileService;
	@Autowired
	private ISecondClassifyService secondClassifyService;
	@PersistenceContext
    public EntityManager entityManager;

	@Override
	@Transactional
	public Content deleteLogic(Long id) {
		Content cp = jpaRepository.getOne(id);
		jpaRepository.save(cp);
		return cp;
	}

	@Override
	@Transactional
	public Content merge(Content model) {
		Content dbo = jpaRepository.getOne(model.getId().longValue());
		CopyUtils.copyProperties(model, dbo);
		return jpaRepository.save(dbo);
	}

	/**
	 * 通过内容id获取内容对象
	 * @param contentId
	 * @return
	 */
	@Override
	public Content findByContentId(String contentId) {
		return contentDao.findByContentId(contentId);
	}

	/**
	 * 通过内容id获取内容对象
	 * @param contentId
	 * @return
	 */
	@Override
	public PrdContDetailVo findPrdContDetailVo(String contentId) throws IOException {
		List<ImageVo> img=null;
		if(StringUtils.isNotBlank(contentId)){
			img=imageService.getImagesWithoutWebp(contentId);
		}
		return new PrdContDetailVo(null,contentDao.findByContentId(contentId),img);
	}
	
	@Override
	public Content findWholeByContentId(String contentId) {
		Content c = contentDao.findByContentId(contentId);
		List<MediaFile> list = mediaFileService.findByContentId(contentId);
		List<MediaFileFromXml> mediaFileList = new ArrayList<MediaFileFromXml>();
		for (MediaFile mf : list) {
            if (c != null) {
            	MediaFileFromXml mediaFile = new MediaFileFromXml();
                if (mf.getMediaUsageCode() != null) {
                    BeanUtils.copyProperties(mf, mediaFile);
                    c.getMediaUsageCodeList().add(mf.getMediaUsageCode());
                }
                mediaFileList.add(mediaFile);
            }
        }
		c.setMediaFileList(mediaFileList);
		
		List<SecondClassify> scs = secondClassifyService.findAllByContentId(c.getContentId());
		c.setSecondClassifyList(scs);

        List<DisplayFile> dfs = displayFileService.findByContentId(c.getContentId());
        List<DisplayFileFromXml> displayFileList = new ArrayList<DisplayFileFromXml>();
        if (c.getDisplayFileList() != null && c.getDisplayFileList().size() > 0) {
            for (DisplayFile df : dfs) {
            	DisplayFileFromXml fromXml = new DisplayFileFromXml();
                BeanUtils.copyProperties(df, fromXml);
                displayFileList.add(fromXml);
            }
        }
        c.setDisplayFileList(displayFileList);
		return c;
	}


	@Override
	public ContentMinBo getBcIdInfo(PrdCont prdCont){
		return getJobNest(null, null, null, null, null);

	}
	private ContentMinBo getJobNest(PrdCont prdCont,Content content ,Content parentContent,String forcePrdInfoBcIds,String freeAuditBcIds){

		return new ContentMinBo(1L,"2",true);
	}

	@Override
	public Page<ContentPojo> findAll(ContentPojo entity, int page, int rows, String sord, String sidx) {
		StringBuffer condition=sqlStringWhere(entity,sord,sidx);
		Object o = entityManager
				.createNativeQuery("select count(*) from ( " + condition.toString() + " ) a").getSingleResult();
		int count = Convert.toInt(o);
		Pageable pageable = getPageable(page - 1, rows, sord, sidx);

		if(count>0){
			Query query=entityManager.createNativeQuery(condition.toString());
			query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
			query.setMaxResults(pageable.getPageSize());
			List<Object[]> resultList=query.getResultList();
			List<ContentPojo> list = getList(resultList);
			PageImpl<ContentPojo> result=new PageImpl<>(list,pageable,count);
			entityManager.close();
			return result;
		}
		entityManager.close();
		return Page.empty(pageable);
	}

	@Override
	public List<PrdContMinVo> getPrdContList(String contentId) {
		if(StringUtils.isBlank(contentId)){
			return new ArrayList<>();
		}
		List<PrdContMinVo> list=new ArrayList<>();
		PrdCont prdCont=new PrdCont();
		prdCont.setContentId(contentId);
		List<PrdCont> prdContList=prdContDao.findAll(Example.of(prdCont));
		//节目表生产数据上亿  内容也不少 凑合用下试试,不行重新调整 gzxx
		String sql="  select pc.PRD_CONT_ID,pi.PRDINFOID,pi.NAME,fi.FIRST_PRODUCT_NAME,pp.PRODUCT_INFO_PACKAGE_NAME,pc.CONTENT_ID,pc.MMS_ID  " +
				"from PRD_CONT pc, CONTENT c ,PRD_INFO pi " +
				"left join FIRST_PRODUCT_INFO_PACKAGE fi  on pi.FIRST_PRODUCT_INFO_PACKAGE_ID=fi.FIRST_PRODUCT_ID " +
				"left join PRODUCT_INFO_PACKAGE pp  on pi.PRODUCT_INFO_PACKAGE_ID=pp.PRODUCT_INFO_PACKAGE_ID " +
				"where pc.CONTENT_ID = C.CONTENT_ID  and pi.PRDINFOID=pc.PRD_INFO_ID  AND c.STATUS <> 2 AND pc.file_action <> 2 AND pc.IS_DELETE = 0" +
				"  and pc.CONTENT_ID='"+contentId+"'";
		Query query=entityManager.createNativeQuery(sql);
		List<Object[]> resultList=query.getResultList();
		if(resultList!=null && resultList.size()>0){
			for (Object[] objs:resultList) {
				PrdContMinVo prdContMinVo=new PrdContMinVo();
				prdContMinVo.setPrdContId(StringUtil.nullToLong(objs[0]));
				prdContMinVo.setPrdInfoId(StringUtil.nullToLong(objs[1]));
				prdContMinVo.setPrdInfoName(StringUtil.nullToString(objs[2]));
				prdContMinVo.setFirstName(StringUtil.nullToString(objs[3]));
				prdContMinVo.setPackageName(StringUtil.nullToString(objs[4]));
				prdContMinVo.setContentId(StringUtil.nullToString(objs[5]));
				prdContMinVo.setMmsId(StringUtil.nullToString(objs[6]));
				list.add(prdContMinVo);
			}
		}
		return list;
	}


	public List<ContentPojo> getList(List<Object[]> resultList){
		List<ContentPojo> list=new ArrayList<>();
		for(Object[] obj:resultList){
			ContentPojo pojo=new ContentPojo();
			pojo.setContentId(Convert.toStr(obj[0]));
			pojo.setName(Convert.toStr(obj[1]));
			pojo.setStatus(Convert.toLong(obj[2]));
			pojo.setCopyrightCpid(Convert.toStr(obj[3]));
			pojo.setKeyWords(Convert.toStr(obj[4]));
			pojo.setCopyrightType(Convert.toStr(obj[5]));
			pojo.setFeeType(Convert.toStr(obj[6]));
			pojo.setCreateTime(Convert.toStr(obj[7]));
			pojo.setId(Convert.toLong(obj[8]));
			pojo.setAssetId(Convert.toStr(obj[9]));
			pojo.setCategory(Convert.toStr(obj[10]));
			pojo.setFormType(Convert.toStr(obj[11]));
			pojo.setType(Convert.toStr(obj[12]));
			pojo.setMovieLibId(Convert.toStr(obj[13]));
			pojo.setLastModifyTime(Convert.toStr(obj[14]));
			pojo.setDisplayType(Convert.toStr(obj[15]));
			pojo.setScope(Convert.toStr(obj[16]));
			pojo.setCduration(Convert.toStr(obj[17]));
			pojo.setNcpId(Convert.toStr(obj[18]));
			pojo.setMiguPublish(Convert.toStr(obj[19]));
			pojo.setBcLicense(Convert.toStr(obj[20]));
			pojo.setInfluence(Convert.toStr(obj[21]));
			pojo.setOriPublish(Convert.toStr(obj[22]));
			pojo.setBeginDate(Convert.toStr(obj[23]));
			pojo.setEndDate(Convert.toStr(obj[24]));
			pojo.setArea(Convert.toStr(obj[25]));
			pojo.setTerminal(Convert.toStr(obj[26]));
			pojo.setIntegrity(Convert.toStr(obj[27]));
			pojo.setOutput(Convert.toStr(obj[28]));
			pojo.setClarity(Convert.toStr(obj[29]));
			pojo.setNeedDRM(Convert.toStr(obj[30]));
			pojo.setAuthorizationWay(Convert.toStr(obj[31]));
			pojo.setWay(Convert.toStr(obj[32]));
			pojo.setSupport(Convert.toStr(obj[33]));
			pojo.setChain(Convert.toStr(obj[34]));
			pojo.setCopy(Convert.toStr(obj[35]));
			pojo.setAccessPlatFormType(Convert.toStr(obj[36]));
			List<String> temp=new ArrayList<>();
			try {
				temp = contentDao.findPrdInfoByContent(pojo.getContentId());
			}catch (Exception e){
				//本地数据库中数据不准确，导致报错  ORA-01489: 字符串连接的结果过长
				// 真实数据库并不会报错
			}
			if(temp.size()>0 && temp != null){
				pojo.setPrdInfoNames(temp.get(0));
			}
			list.add(pojo);
		}
		return list;
	}


	public StringBuffer sqlStringWhere(ContentPojo entity, String sord, String sidx){
		StringBuffer condition=new StringBuffer();
		String sql="select c.content_id, c.name, c.status, c.copyright_cpid, c.key_words, c.copyright_type, c.fee_type, c.create_time, c.id, " +
				"c.asset_id, c.category, c.form_type, c.type, c.movie_lib_id, c.last_modify_time, c.display_type, c.scope, c.cduration, c.n_cpId, " +
				"c.migu_Publish, c.bc_License, c.influence, c.ori_Publish, c.begin_Date, c.end_Date, c.area, c.terminal, c.integrity, c.output, " +
				"c.clarity, c.need_DRM, c.authorization_Way, c.way, c.support, c.chain, c.copy,c.ACCESS_PLATFORM_TYPE from CONTENT c where 1=1 ";
		condition.append(sql);

		if(StrUtil.isNotBlank(entity.getContentId())){
			condition.append("and c.content_id= '"+entity.getContentId()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getAssetId())){
			condition.append("and c.asset_id= '"+entity.getAssetId()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getName())){
			condition.append("and c.name like '%"+entity.getName()+"%' ");
		}
		if(StrUtil.isNotBlank(entity.getFormType())){
			condition.append("and c.form_type= '"+entity.getFormType()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getFeeType())){
			condition.append("and c.fee_type= '"+entity.getFeeType()+"' ");
		}
		if(entity.getStatus()!=null){
			condition.append("and c.status = "+entity.getStatus()+" ");
		}
		if(StrUtil.isNotBlank(entity.getDisplayType())){
			condition.append("and c.display_type= '"+entity.getDisplayType()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getCopyrightType())){
			condition.append("and c.copyright_type= '"+entity.getCopyrightType()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getScope())){
			condition.append("and c.scope = '"+entity.getScope()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getBeginDate())){
			condition.append("and c.LAST_MODIFY_TIME >= '"+entity.getBeginDate()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getEndDate())){
			condition.append("and c.LAST_MODIFY_TIME <= '"+entity.getEndDate()+"' ");
		}
		if(StrUtil.isNotBlank(entity.getCopyrightCpid())){
			condition.append("and c.copyright_cpid = '"+entity.getCopyrightCpid()+"' ");
		}
		if(entity.getPrdInfoId() != null && !"".equals(entity.getPrdInfoId())){
			condition.append(" AND EXISTS (SELECT 1 FROM prd_cont pc WHERE pc.content_id = c.content_id AND pc.prd_info_id = "+entity.getPrdInfoId()+" AND pc.is_delete = 0)");
		}
		if (entity.getPrdContId() != null && !"".equals(entity.getPrdContId())) {
			condition.append(" AND EXISTS (SELECT 1 FROM prd_cont pc2 WHERE pc2.content_id = c.content_id AND pc2.prd_cont_id = "+entity.getPrdContId()+" AND pc2.is_delete = 0)");
		}

		//内容类型：爱情|喜剧；内容形态：预告
		if (StrUtil.isNotBlank(entity.getSecondClassify())){
			String sc = entity.getSecondClassify().replaceAll("：", ":").replaceAll("；", ";");
			if (sc.indexOf(":") > -1) {
				String[] sca = sc.split(";");
				if (sca != null && sca.length > 0) {
					for (String scc : sca) {
						String[] scca = scc.split(":");
						if (scca != null && scca.length == 2) {
							String key = scca[0];
							String value = scca[1];

							if(value.indexOf("|") > -1) {
								String[] vala = value.split("\\|");
								if(vala != null && vala.length > 0) {
									condition.append(" and exists (select 1 from SECOND_CLASSIFY sc where sc.CONTENT_ID = c.CONTENT_ID and sc.CLASSIFY_KEY = '"+key+"' and ( ");
									for (int ii = 0; ii < vala.length; ii++) {
										condition.append(" sc.CLASSIFY_VALUE = '"+vala[ii]+"' ");
										if (ii < vala.length - 1) {
											condition.append(" or ");
										}
									}
									condition.append(")) ");
								}
							} else {
								condition.append(" and exists (select 1 from SECOND_CLASSIFY sc where sc.CONTENT_ID = c.CONTENT_ID and sc.CLASSIFY_KEY = '"+key+"' and sc.CLASSIFY_VALUE = '"+value+"') ");
							}
						}
					}
				}

			}
		}



		condition.append("order by "+sidx+" "+sord);
		return condition;
	}

}